package com.mb.ext.msg;

import com.alibaba.fastjson.JSONObject;
import com.mb.ext.core.util.WechatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.mb.ext.core.constant.WechatConstants;
import com.mb.ext.core.dao.SettingDAO;
import com.mb.ext.core.entity.SettingEntity;
import com.mb.ext.core.util.WXInitializeUtility;
import com.mb.framework.util.log.LogHelper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class WxSuscribeMessageSender {

	@Autowired
	@Qualifier("settingDAO")
	private SettingDAO settingDAO;

	@Autowired
	private WXInitializeUtility wxInitializeUtility;

	@Autowired
	private WechatUtil wechatUtil;


	private final static LogHelper logger = LogHelper.getInstance(WxSuscribeMessageSender.class.getName());


	/**
	 * 用户支付成功(提示团长)
	 * @param appId
	 * @param appSecret
	 * @param openId
	 * @param orderAmout
	 * @param phoneNum
	 * @param productName
	 * @param userName
	 * @return
	 */
	public String sendPayToMerchantMsg(String appId, String appSecret,String openId, String orderAmout,
									   String phoneNum, String productName, String userName,String orderId){
//		String templateId = "PFmlgTUWp25SpEZcOieuD9SfbODFm5y5eBgSkin-ec0";
		String templateId = "UIZ_7uKdF6owlVxdDcmzzhe56P-Jqz-ndDgdcsgrXsw";
		String msg = "";
		try {
			Map<Object, WeChatTemplateMsg> sendMap = new HashMap<>();
//			sendMap.put("first", new WeChatTemplateMsg(userName+" 购买成功"));
//			sendMap.put("keyword1", new WeChatTemplateMsg(orderId));
//			sendMap.put("keyword2", new WeChatTemplateMsg(productName));
//			sendMap.put("keyword3", new WeChatTemplateMsg(orderAmout));
//			sendMap.put("keyword4", new WeChatTemplateMsg(orderAmout));
//			sendMap.put("keyword5", new WeChatTemplateMsg(phoneNum));
//			sendMap.put("remark", new WeChatTemplateMsg("可在团长管理-我的-订单中查看详情"));
			sendMap.put("character_string6", new WeChatTemplateMsg(orderId));
			sendMap.put("thing2", new WeChatTemplateMsg(productName));
			sendMap.put("amount10", new WeChatTemplateMsg(orderAmout));
			sendMap.put("phone_number16", new WeChatTemplateMsg(phoneNum));
			sendMap.put("thing23", new WeChatTemplateMsg("可在团长管理-我的-订单中查看详情"));

			Map<String, Object> map = getNotifyMapWithMiniProm(appId,openId, templateId, sendMap);
			String jsonMsg=JSON.toJSONString(map);
			msg = sendTemplateMsg(appId, appSecret, jsonMsg);
			logger.info("发送订单发货订阅消息请求: "+jsonMsg);

			logger.info("发送订单发货订阅消息返回: "+msg);

		}catch(Exception e) {
			e.printStackTrace();
			logger.error("发送订单发货订阅消息发生异常： "+e.getMessage());
		}
		return msg;
	}

	/**
	 * 用户支付成功(提示团长微信公众号)
	 * @param openId
	 * @param orderAmout
	 * @param phoneNum
	 * @param productName
	 * @param userName
	 * @return
	 */
	public String sendPayToGzhMerchantMsg(String openId, String orderAmout,
									   String phoneNum, String productName, String userName,String orderId) throws IOException {
		String result = "";
		String templateId = "YNp1kcSwVwYBbujEo7llFAFp2tKxIW5U4oryo7-XLSY";
		JSONObject jsonObject1 = new JSONObject();
		JSONObject jsonObject11 = new JSONObject();
		jsonObject11.put("value",orderId);
		jsonObject1.put("character_string12", jsonObject11);
		jsonObject11 = new JSONObject();
		jsonObject11.put("value",productName);
		jsonObject1.put("thing11", jsonObject11);
		jsonObject11 = new JSONObject();
		jsonObject11.put("value",orderAmout);
		jsonObject1.put("amount13", jsonObject11);
		jsonObject11 = new JSONObject();
		jsonObject11.put("value",phoneNum);
		jsonObject1.put("phone_number17", jsonObject11);
		wechatUtil.sendTemplateMessage(templateId,openId,jsonObject1);
		return result;
	}

	private Map<String, Object> getNotifyMapWithMiniProm(String appId,String openId, String templateId, Map<Object, WeChatTemplateMsg> sendMap) {
		Map<String, Object> sendBody = new HashMap<>();
		Map<String, Object> mp_template_msg = new HashMap<>();
		sendBody.put("touser", openId); // openId
		sendBody.put("template_id", templateId);     // 模板Id
		sendBody.put("data", sendMap);
		sendBody.put("miniprogram_state","formal");
		sendBody.put("lang","zh_CN");
//		sendBody.put("mp_template_msg",mp_template_msg);
//		mp_template_msg.put("template_id", templateId);     // 模板Id
//		mp_template_msg.put("appid", appId);
//		mp_template_msg.put("url", "https://tg.jzjunhao.com/groupbuy-merchant-mobile/#/pages/user/user");
//		mp_template_msg.put("url", "https://tg.yxstg.cn/merchant/#/pages/user/user");
//		mp_template_msg.put("data", sendMap);
		return sendBody;
	}
//
	class WeChatTemplateMsg {
		private String value;

		public WeChatTemplateMsg(){}

		public WeChatTemplateMsg(String value){
			this.value = value;
		}

		public String getValue() {
			return value;
		}

		public void setValue(String value) {
			this.value = value;
		}
	}

	public String sendMsg(String appId, String appSecret,String jsonStr){
		String token = wxInitializeUtility.getEffectiveToken(appId, appSecret);

		String url=WechatConstants.URL_WX_SEND_SUSCRIBE_MSG;

		url=url.replace("ACCESS_TOKEN", token);

		logger.info("微信请求地址： "+url);

		String msg=	HttpClientHelper.postJsonObject(url, jsonStr);

		return msg;
	}
	public String sendTemplateMsg(String appId, String appSecret,String jsonStr){
		String token = wxInitializeUtility.getEffectiveToken(appId, appSecret);

		String url=WechatConstants.URL_WX_SEND_TEMPLATE_MSG;

		url=url.replace("ACCESS_TOKEN", token);

		logger.info("微信请求地址： "+url);

		String msg=	HttpClientHelper.postJsonObject(url, jsonStr);

		return msg;
	}


	public String sendOrderPayedMsg(String appId, String appSecret,String openId, String orderNo, String paymentTime,
									String productName, String productAmount, String memo){
		String msg = "";
		try {
			WXSuscribeMessage message = new WXSuscribeMessage();
			SettingEntity settingEntity = settingDAO.getSettingByName("WX_SUSCRIBE_MSG_ORDER_PAY");
			String templateId = settingEntity.getValue();
			message.setTemplate_id(templateId);
			message.setTouser(openId);

			WXSuscribeMessageDataOrderPayed data = new WXSuscribeMessageDataOrderPayed();
			WXSuscribeMessageDataValue orderValule = new WXSuscribeMessageDataValue();
			orderValule.setValue(orderNo);
			data.setCharacter_string1(orderValule);

			WXSuscribeMessageDataValue dateValule = new WXSuscribeMessageDataValue();
			dateValule.setValue(paymentTime);
			data.setDate2(dateValule);

			WXSuscribeMessageDataValue productValule = new WXSuscribeMessageDataValue();
			productValule.setValue(productName);
			data.setThing3(productValule);

			WXSuscribeMessageDataValue amountValule = new WXSuscribeMessageDataValue();
			amountValule.setValue(productAmount);
			data.setAmount4(amountValule);

			WXSuscribeMessageDataValue memoValule = new WXSuscribeMessageDataValue();
			memoValule.setValue(memo);
			data.setThing7(memoValule);

			message.setData(data);
			String jsonMsg=JSON.toJSONString(message);

			logger.info("发送订单支付订阅消息请求: "+jsonMsg);

			msg = sendMsg(appId, appSecret, jsonMsg);

			logger.info("发送订单支付订阅消息返回: "+msg);

		}catch(Exception e) {
			e.printStackTrace();
			logger.error("发送订单支付成功模板消息发生异常： "+e.getMessage());
		}
		return msg;
	}



	public String sendOrderDeliveredMsg(String appId, String appSecret,String openId, String orderNo, String deliverTime, String productName, String courierName, String courierId){
		String msg = "";
		try {
			WXSuscribeMessage message = new WXSuscribeMessage();
			SettingEntity settingEntity = settingDAO.getSettingByName("WX_SUSCRIBE_MSG_ORDER_DELIVERED");
			String templateId = settingEntity.getValue();
			message.setTemplate_id(templateId);
			message.setTouser(openId);

			WXSuscribeMessageDataOrderDelivered data = new WXSuscribeMessageDataOrderDelivered();
			WXSuscribeMessageDataValue orderValule = new WXSuscribeMessageDataValue();
			orderValule.setValue(orderNo);
			data.setCharacter_string1(orderValule);

			WXSuscribeMessageDataValue dateValule = new WXSuscribeMessageDataValue();
			dateValule.setValue(deliverTime);
			data.setDate5(dateValule);

			WXSuscribeMessageDataValue productValule = new WXSuscribeMessageDataValue();
			productValule.setValue(productName);
			data.setThing2(productValule);

			WXSuscribeMessageDataValue courierNameValule = new WXSuscribeMessageDataValue();
			courierNameValule.setValue(courierName);
			data.setThing7(courierNameValule);

			WXSuscribeMessageDataValue courierIdValule = new WXSuscribeMessageDataValue();
			courierIdValule.setValue(courierId);
			data.setCharacter_string4(courierIdValule);

			message.setData(data);
			String jsonMsg=JSON.toJSONString(message);

			logger.info("发送订单发货订阅消息请求: "+jsonMsg);

			msg = sendMsg(appId, appSecret, jsonMsg);

			logger.info("发送订单发货订阅消息返回: "+msg);

		}catch(Exception e) {
			e.printStackTrace();
			logger.error("发送订单发货订阅消息发生异常： "+e.getMessage());
		}
		return msg;
	}

	public String sendOrderReturnMsg(String appId, String appSecret,String openId, String orderNo, String returnTime, String productName, String returnAmount, String returnStatus){
		String msg = "";
		try {
			WXSuscribeMessage message = new WXSuscribeMessage();
			SettingEntity settingEntity = settingDAO.getSettingByName("WX_SUSCRIBE_MSG_ORDER_RETURN");
			String templateId = settingEntity.getValue();
			message.setTemplate_id(templateId);
			message.setTouser(openId);

			WXSuscribeMessageDataOrderReturn data = new WXSuscribeMessageDataOrderReturn();
			WXSuscribeMessageDataValue orderValule = new WXSuscribeMessageDataValue();
			orderValule.setValue(orderNo);
			data.setCharacter_string4(orderValule);

			WXSuscribeMessageDataValue dateValule = new WXSuscribeMessageDataValue();
			dateValule.setValue(returnTime);
			data.setDate3(dateValule);

			WXSuscribeMessageDataValue productValule = new WXSuscribeMessageDataValue();
			productValule.setValue(productName);
			data.setThing5(productValule);

			WXSuscribeMessageDataValue amountValule = new WXSuscribeMessageDataValue();
			amountValule.setValue(returnAmount);
			data.setAmount2(amountValule);

			WXSuscribeMessageDataValue memoValule = new WXSuscribeMessageDataValue();
			memoValule.setValue(returnStatus);
			data.setThing6(memoValule);

			message.setData(data);
			String jsonMsg=JSON.toJSONString(message);

			logger.info("发送退款订阅消息请求: "+jsonMsg);

			msg = sendMsg(appId, appSecret, jsonMsg);

			logger.info("发送退款订阅消息返回: "+msg);

		}catch(Exception e) {
			e.printStackTrace();
			logger.error("发送退款订阅消息发生异常： "+e.getMessage());
		}
		return msg;
	}

	public String sendAwardMsg(String appId, String appSecret,String openId, String awardType, String awardAmount, String awardDesc){
		String msg = "";
		try {
			WXSuscribeMessage message = new WXSuscribeMessage();
			SettingEntity settingEntity = settingDAO.getSettingByName("WX_SUSCRIBE_MSG_AWARD");
			String templateId = settingEntity.getValue();
			message.setTemplate_id(templateId);
			message.setTouser(openId);

			WXSuscribeMessageDataAward data = new WXSuscribeMessageDataAward();
			WXSuscribeMessageDataValue awardTypeValule = new WXSuscribeMessageDataValue();
			awardTypeValule.setValue(awardType);
			data.setThing1(awardTypeValule);

			WXSuscribeMessageDataValue awardAmountValule = new WXSuscribeMessageDataValue();
			awardAmountValule.setValue(awardAmount);
			data.setThing2(awardAmountValule);

			WXSuscribeMessageDataValue awardDescValule = new WXSuscribeMessageDataValue();
			awardDescValule.setValue(awardDesc);
			data.setThing3(awardDescValule);

			message.setData(data);
			String jsonMsg=JSON.toJSONString(message);

			logger.info("发送奖励订阅消息请求: "+jsonMsg);

			msg = sendMsg(appId, appSecret, jsonMsg);

			logger.info("发送奖励订阅消息返回: "+msg);

		}catch(Exception e) {
			e.printStackTrace();
			logger.error("发送奖励订阅消息发生异常： "+e.getMessage());
		}
		return msg;
	}
}
